package com.abu.classes.config;


import cn.hutool.core.util.StrUtil;
import com.abu.classes.utils.manager.JwtUtils;
import com.abu.classes.utils.portal.JProperties;
import com.abu.classes.utils.portal.JUtils;
import com.abu.classes.vo.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
@EnableConfigurationProperties(JProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private JProperties jProperties;

    private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();
    private static final ThreadLocal<UserInfo> THREAD_LOCAL_USERINFO = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        防止Csrf（防止盗链）
        String referer = request.getHeader("Referer");
        if (StrUtil.isBlank(referer) || !referer.startsWith("http://localhost")) {
            return false;
        }
//      约定： 前后台系统都将token放在请求头 token:xxxx 中，token以UserLogin开头则代表前台用户登录
        String token = request.getHeader("token");
//        判断是否为空
        if (StrUtil.isBlank(token)) {
            log.info("token为空");
            return false;
        }
        String hasUserLoginPrefix = "UserLogin";
        String hasManagerLoginPrefix = "ManagerLogin";
//        判断是否是前台用户登录
        if (token.startsWith(hasUserLoginPrefix)) {
            String realUserToken = StringUtils.substringAfter(token, hasUserLoginPrefix);
            Map<String, Object> infoFromToken = JUtils.getInfoFromToken(realUserToken, jProperties.getPublicKey());
            Long userId = (Long) infoFromToken.get("userId");
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            THREAD_LOCAL_USERINFO.set(userInfo);
            return true;
        } else if (token.startsWith(hasManagerLoginPrefix)) {
//      后台系统登录
            String realUserToken = StringUtils.substringAfter(token, hasManagerLoginPrefix);
            Map<String, String> managerInfoMap = jwtUtils.getInfoFromToken(realUserToken);
            String managerId = managerInfoMap.get("managerId");
            THREAD_LOCAL.set(managerId);
            return true;
        }
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        THREAD_LOCAL.remove();
        THREAD_LOCAL_USERINFO.remove();
    }

    public static String getManagerId() {
        return THREAD_LOCAL.get();
    }

    public static UserInfo getUserInfo() {
        return THREAD_LOCAL_USERINFO.get();
    }

}
